package com.kiwi.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.support.DaoSupport;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.springframework.util.Assert.notNull;

@Component("IndianaDao")
public class IndianaDao extends DaoSupport {

    private SqlSession sqlSession;
    private boolean externalSqlSession;
    @Autowired(required=false)
    public final void setMySqlSessionFactory(@Qualifier("IndianaSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        //this.setSqlSessionFactory(sqlSessionFactory);
        if(!this.externalSqlSession){
            this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
        }
    }
    @Autowired(required=false)
    public final void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
        this.sqlSession = sqlSessionTemplate;
        this.externalSqlSession = true;
    }
    public int delete(String sqlId,Object obj){
        return getSqlSession().delete(sqlId,obj);
    }
    public int insertOrUpdate(String sqlId, Object obj){
        return getSqlSession().update(sqlId,obj);
    }
    @SuppressWarnings("rawtypes")
    public List selectList(String sqlId, Object parameter){
        return getSqlSession().selectList(sqlId, parameter);
    }
    public Object selectOne(String sqlId, Object parameter){
        return getSqlSession().selectOne(sqlId, parameter);
    }
    @Override
    protected void checkDaoConfig() throws IllegalArgumentException {
        // TODO Auto-generated method stub
        notNull(this.sqlSession, "Property sqlSessionFactory or sqlSessionTemplate are required");
    }

    public SqlSession getSqlSession() {
        return sqlSession;
    }

}
